from flask import Flask, request
from server.func.verify import verify_user, create_temp_key, verify_key
from server.func.database import *
from server.func.FileOperate import get_file_path

app = Flask(__name__)


update_flag = {}  # 主页面刷新标志
sound_flag = {}  # 提示音标志


def ensure_dir():
    path = "server/sql/"
    dirs = ["files", "groups", "history", "img_buf", "users"]
    if not os.path.exists(path):
        os.mkdir(path)
    for dir in dirs:
        if not os.path.exists(path + dir):
            os.mkdir(path + dir)


@app.route('/test/', methods=['POST', 'GET'])
def test():
    """测试"""
    print(request.url_root)
    print(request.form)
    print(request.args)
    print(request.cookies)
    print(request.files)
    print(request.method)
    print(request.json)
    return "test!"


@app.route('/get_update/', methods=['POST', 'GET'])
def get_update():
    """获取主界面是否刷新的标志"""
    global update_flag
    global sound_flag
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    key = client_post["key"]
    if verify_key(uid, key):
        reply["Remote_landing"] = False
    else:
        reply["Remote_landing"] = True
    if uid in update_flag.keys():
        reply["status"] = update_flag[uid]
        update_flag[uid] = False
    else:
        reply["status"] = False
    if uid in sound_flag.keys():
        reply["sound"] = sound_flag[uid]
        sound_flag[uid] = False
    else:
        reply["sound"] = False
    return reply


@app.route('/login/', methods=['POST'])
def login():
    """登陆"""
    global update_flag
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    password = client_post["password"]
    if verify_user(uid, password):
        reply["status"] = True
        reply["key"] = create_temp_key(uid)
        reply["info"] = u"登陆成功!"
        update_flag[uid] = True
    else:
        reply["status"] = False
        reply["key"] = ""
        reply["info"] = u"用户名或密码错误"
    return reply


@app.route('/register/', methods=['POST'])
def register():
    """注册"""
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    password = client_post["password"]
    name = client_post["name"]
    if add_user(uid, password, name):
        reply["status"] = True
        reply["info"] = u"注册成功!"
    else:
        reply["status"] = False
        reply["info"] = u"uid已存在"
    return reply


@app.route('/change_new_friend_num/', methods=['POST'])
def change_new_friend_num_():
    """改变新朋友消息数"""
    global update_flag
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    key = client_post["key"]
    num = client_post["NewFriend"]
    if verify_key(uid, key):
        status = change_new_friend_num(uid, num)
        reply["status"] = status
        update_flag[uid] = True
    else:
        reply["status"] = False
    return reply


@app.route("/user_main/", methods=['POST', 'GET'])
def user_main():
    """获取用户主界面参数"""
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    key = client_post["key"]
    if verify_key(uid, key):
        data = get_user_main(uid)
        if data:
            reply["status"] = True
            reply["Friend"] = data[0]
            reply["Group"] = data[1]
            reply["NewFriend"] = data[2]
        else:
            reply["status"] = False
            reply["Friend"] = []
            reply["Group"] = []
            reply["NewFriend"] = 0
    else:
        reply["status"] = False
        reply["Friend"] = []
        reply["Group"] = []
        reply["NewFriend"] = 0
    return reply


@app.route('/get_user_info/', methods=['POST', 'GET'])
def get_user_info_():
    """获取用户信息"""
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    data = get_user_info(uid)
    if data:
        reply["status"] = True
        reply["name"] = data[0]
        reply["img"] = data[1]
        reply["sex"] = data[2]
        reply["search_accept"] = data[3]
        reply["explain"] = data[4]
    else:
        reply["status"] = False
    return reply


@app.route('/get_img/', methods=['POST', 'GET'])
def get_img_():
    """下载头像"""
    reply = dict()
    client_post = request.json
    img_path = client_post["img_path"]
    img = get_img(img_path)
    reply["img"] = img
    return reply


@app.route('/save_img/', methods=['POST'])
def save_img_():
    """上传头像"""
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    img = client_post["img"]
    mode = client_post["mode"]
    if mode == "friend":
        img_path = "u"+str(uid)+".png"
        reply["status"] = save_img(img_path, img)
    else:
        img_path = "g" + str(uid) + ".png"
        reply["status"] = save_img(img_path, img)
    return reply


@app.route('/change_user_info/', methods=['POST'])
def change_user_info_():
    """修改用户信息"""
    global update_flag
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    key = client_post["key"]
    info = client_post["info"]
    if verify_key(uid, key):
        reply["status"] = change_user_info(uid, info)
        update_flag[uid] = True
    else:
        reply["status"] = False
    return reply


@app.route('/change_password/', methods=['POST'])
def change_password_():
    """修改密码"""
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    key = client_post["key"]
    pswd = client_post["pswd"]
    new_pswd = client_post["new_pswd"]
    if verify_key(uid, key):
        if verify_user(uid, pswd):
            reply["status"] = change_password(uid, new_pswd)
            reply["info"] = u"修改成功!"
        else:
            reply["status"] = False
            reply["info"] = u"原密码错误!"
    else:
        reply["status"] = False
        reply["info"] = u"用户校验错误!"
    return reply


@app.route('/search/', methods=['POST', 'GET'])
def search_():
    """ 查询群聊或用户"""
    reply = dict()
    client_post = request.json
    content = client_post["content"]
    users, groups = search(content)
    reply["User"] = users
    reply["Group"] = groups
    return reply


@app.route('/delete_friend/', methods=['POST'])
def delete_friend_():
    """删除朋友"""
    global update_flag
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    friend_uid = client_post["friend_uid"]
    key = client_post["key"]
    if verify_key(uid, key):
        reply["status"] = delete_friend(uid, friend_uid)
        update_flag[uid] = True
        update_flag[friend_uid] = True
    else:
        reply["status"] = False
    return reply


@app.route('/change_remarks/', methods=['POST'])
def change_remarks_():
    """更改好友备注"""
    global update_flag
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    friend_uid = client_post["friend_uid"]
    name = client_post["name"]
    key = client_post["key"]
    if verify_key(uid, key):
        reply["status"] = change_remarks(uid, friend_uid, name)
        update_flag[uid] = True
    else:
        reply["status"] = False
    return reply


@app.route('/is_friend/', methods=['POST', 'GET'])
def is_friend_():
    """是不是好友"""
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    friend_uid = client_post["friend_uid"]
    key = client_post["key"]
    if verify_key(uid, key):
        reply["is_friend"] = is_friend(uid, friend_uid)
        reply["status"] = True
    else:
        reply["is_friend"] = False
        reply["status"] = False
    return reply


@app.route('/get_remarks/', methods=['POST', 'GET'])
def get_remarks_():
    """查询备注"""
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    friend_uid = client_post["friend_uid"]
    key = client_post["key"]
    if verify_key(uid, key):
        reply["remarks"] = get_remarks(uid, friend_uid)
        reply["status"] = True
    else:
        reply["remarks"] = None
        reply["status"] = False
    return reply


@app.route('/get_new_friend/', methods=['POST', 'GET'])
def get_new_friend_():
    """获取新朋友通知"""
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    key = client_post["key"]
    if verify_key(uid, key):
        users, groups = get_new_friend(uid)
        reply["User"] = users
        reply["Group"] = groups
    else:
        reply["User"] = []
        reply["Group"] = []
    return reply


@app.route('/clear_new_friend/', methods=['POST'])
def clear_new_friend_():
    """清空新朋友消息"""
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    key = client_post["key"]
    mode = client_post["mode"]
    if verify_key(uid, key):
        reply["status"] = clear_new_friend(uid, mode)
    else:
        reply["status"] = False
    return reply


@app.route('/friend_application/', methods=['POST'])
def friend_application_():
    """好友申请"""
    global update_flag
    global sound_flag
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    key = client_post["key"]
    target_uid = client_post["target_uid"]
    if verify_key(uid, key):
        reply["status"] = friend_application(uid, target_uid)
        update_flag[target_uid] = True
        sound_flag[target_uid] = True
    else:
        reply["status"] = False
    return reply


@app.route('/response_friend_application/', methods=['POST'])
def response_friend_application_():
    """回复好友申请"""
    global update_flag
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    key = client_post["key"]
    from_uid = client_post["from_uid"]
    response = client_post["response"]
    if verify_key(uid, key):
        reply["status"] = response_friend_application(uid, from_uid, response)
        update_flag[uid] = True
        update_flag[from_uid] = True
    else:
        reply["status"] = False
    return reply


@app.route('/get_history/', methods=['POST', 'GET'])
def get_history_():
    """获取历史消息"""
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    key = client_post["key"]
    target = client_post["target"]
    mode = client_post["mode"]
    if verify_key(uid, key):
        reply["status"] = True
        reply["history"] = get_history(uid, target, mode)
    else:
        reply["status"] = False
        reply["history"] = {"history": []}
    return reply


@app.route('/send_message/', methods=['POST'])
def send_message_():
    """发送消息"""
    global update_flag
    global sound_flag
    url = request.root_url
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    key = client_post["key"]
    target = client_post["target"]
    mode = client_post["mode"]
    msg_dic = client_post["message"]
    if verify_key(uid, key):
        if msg_dic["bubble_type"] == "file":
            print(request.files)
            f = request.files['file']
            file_path, text = get_file_path(url, msg_dic["text"])
            f.save(file_path)
            msg_dic["text"] = text
        reply["status"] = send_message(uid, target, mode, msg_dic)
        if mode == "friend":
            update_flag[uid] = True
            update_flag[target] = True
            sound_flag[target] = True
        else:
            update_flag[uid] = True
            for member in get_group_members(target):
                if not member == uid:
                    update_flag[member] = True
                    sound_flag[member] = True
    else:
        reply["status"] = False
    return reply


@app.route('/change_msg_info_num/', methods=['POST'])
def change_msg_info_num_():
    """修改消息通知数量"""
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    key = client_post["key"]
    target = client_post["target"]
    mode = client_post["mode"]
    num = client_post["num"]
    if verify_key(uid, key):
        reply["status"] = change_msg_info_num(uid, target, mode, num)
    else:
        reply["status"] = False
    return reply


@app.route('/add_group/', methods=['POST'])
def add_group_():
    """新建群聊"""
    global update_flag
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    key = client_post["key"]
    name = client_post["name"]
    if verify_key(uid, key):
        update_flag[uid] = True
        reply["status"] = add_group(uid, name)
    else:
        reply["status"] = False
    return reply


@app.route('/get_group_info/', methods=['POST', 'GET'])
def get_group_info_():
    """获取群聊信息"""
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    reply["group"] = get_group_info(uid)
    return reply


@app.route('/change_group_info/', methods=['POST'])
def change_group_info_():
    """修改群聊信息"""
    global update_flag
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    info = client_post["info"]
    reply["status"] = change_group_info(uid, info)
    for member in get_group_members(uid):
        update_flag[member] = True
    return reply


@app.route('/group_application/', methods=['POST'])
def group_application_():
    """群聊申请"""
    global update_flag
    global sound_flag
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    key = client_post["key"]
    target_uid = client_post["group_uid"]
    if verify_key(uid, key):
        reply["status"] = group_application(uid, target_uid)
        master = get_group_master(target_uid)
        update_flag[master] = True
        sound_flag[master] = True
    else:
        reply["status"] = False
    return reply


@app.route('/response_group_application/', methods=['POST'])
def response_group_application_():
    """回复群聊申请"""
    global update_flag
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    key = client_post["key"]
    group_uid = client_post["group_uid"]
    from_uid = client_post["from_uid"]
    response = client_post["response"]
    if verify_key(uid, key):
        reply["status"] = response_group_application(uid, group_uid, from_uid, response)
        update_flag[from_uid] = True
    else:
        reply["status"] = False
    return reply


@app.route('/out_group/', methods=['POST'])
def out_group_():
    global update_flag
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    key = client_post["key"]
    group_uid = client_post["group_uid"]
    if verify_key(uid, key):
        reply["status"] = out_group(group_uid, uid)
        update_flag[uid] = True
    else:
        reply["status"] = False
    return reply


@app.route('/delete_group/', methods=['POST'])
def delete_group_():
    global update_flag
    reply = dict()
    client_post = request.json
    uid = client_post["uid"]
    key = client_post["key"]
    group_uid = client_post["group_uid"]
    if verify_key(uid, key):
        members = get_group_members(group_uid)
        reply["status"] = delete_group(group_uid)
        for member in members:
            update_flag[member] = True
    else:
        reply["status"] = False
    return reply


if __name__ == '__main__':
    ensure_dir()
    app.run(
        debug=True,  # 代码更新是否自动重启
        port=5000,  # 指定端口
        host="127.0.0.1"  # 指定主机（设置0.0.0.0可以通过本地IP访问）
    )
